package com.ydx.Controller;

import com.ydx.entity.PatrolAndShiyanshi;
import com.ydx.service.PatrolService;
import org.apache.poi.ss.usermodel.*;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import jakarta.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/excel")
public class ExcelController {

    @Autowired
    private PatrolService patrolService;

    @RequestMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        String filename = "测试excel.xlsx";
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(filename, "utf-8") + "\"");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        createExcel(response.getOutputStream());
        response.getOutputStream().flush();
    }

    public void createExcel(OutputStream os) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        String sheetName = "巡检记录";
        Sheet sheet = workbook.createSheet(sheetName);

        // 创建表头
        String[] headers = {"日期", "实验室", "负责人", "门窗", "门窗备注", "设备", "设备备注"};
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 获取数据
        List<PatrolAndShiyanshi> records = patrolService.selectMore();
        // 在填充数据的循环中，对日期字段进行处理
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 填充数据
        int rowNum = 1;
        for (PatrolAndShiyanshi record : records) {
            Row row = sheet.createRow(rowNum++);
            Cell dateCell = row.createCell(0);
            dateCell.setCellValue(dateFormat.format(record.getCreattime()));
            row.createCell(1).setCellValue(record.getShiyanshiname());
            row.createCell(2).setCellValue(record.getUsername());
            row.createCell(3).setCellValue(record.getDoor());
            row.createCell(4).setCellValue(record.getDoornotes());
            row.createCell(5).setCellValue(record.getDevice());
            row.createCell(6).setCellValue(record.getDevicenotes());
        }

        workbook.write(os);
        workbook.close();
    }
}

